package com.reguang.datasourceConfig;

import java.util.concurrent.atomic.AtomicInteger;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.druid.support.logging.Log;

import ch.qos.logback.classic.Logger;

/**
 * Title: DynamicDataSourceAspect
 * <p>
 * Description:
 * </p>
 * 
 * @author 路汉腾 2020年2月6日 下午3:48:26
 */

@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Component
@Order(0)
public class DynamicDataSourceAspect {
	private static final Logger logger = (Logger) LoggerFactory.getLogger(DynamicDataSourceAspect.class);
	// 查询类名称
	private final String[] QUERY_PREFIX = { "select", "get", "list", "query" };

	// 在service 层加入aop
	@Pointcut("execution( * com.reguang.service.*.*(..))")
	public void daoAspect() {
	}

	private AtomicInteger integer = new AtomicInteger();


	// 在方法调用前选择 数据源
	@Before("daoAspect()")
	public void switchDataSource(JoinPoint point) {
		Boolean isQueryMethod = isQueryMethod(point.getSignature().getName());
		if (!isQueryMethod) {
			DbContextHolder.setDbType(DbTypeEnum.db1);
			logger.info(point + "");
		} else {
			int i = integer.getAndIncrement();
			if (i % 2 == 0) {
				DbContextHolder.setDbType(DbTypeEnum.db2);
			} else {
				DbContextHolder.setDbType(DbTypeEnum.db3);
			}
			
		}
	}
	
	@After("daoAspect()")
    public void after(JoinPoint point) {
		DbContextHolder.clearDbType();
    }

	// 判断是否是查询类方法
	private Boolean isQueryMethod(String methodName) {
		for (String prefix : QUERY_PREFIX) {
			if (methodName.startsWith(prefix)) {
				return true;
			}
		}
		return false;
	}
}
